package com.unohacha.qqj.fzdr.main.sends;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.qpg.superhttp.SuperHttp;
import com.qpg.superhttp.callback.SimpleCallBack;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.bean.BaseBean;
import com.unohacha.qqj.fzdr.bean.GoodsRealseResultBean;
import com.unohacha.qqj.fzdr.bean.LevelThreeClassBean;
import com.unohacha.qqj.fzdr.bean.citybean.ProvinceBean;
import com.unohacha.qqj.fzdr.imp.MyCallBack;
import com.unohacha.qqj.fzdr.imp.UrlConfig;
import com.unohacha.qqj.fzdr.imp.XUtil;
import com.unohacha.qqj.fzdr.main.LocationYellowSendActivity;
import com.unohacha.qqj.fzdr.util.FastUtils;
import com.unohacha.qqj.fzdr.util.GetJsonDataUtil;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.util.ToastUtils;
import com.unohacha.qqj.fzdr.view.citypickview.CityPickerPopWindow2;
import com.unohacha.qqj.mylibrary.base.BaseActivity;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 物资行情 --->发布
 */
public class SendMaterialMarketActivity extends BaseActivity implements CityPickerPopWindow2.CityPickListener{

    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.common_right_text)
    TextView commonRightText;
    @BindView(R.id.home1_title)
    LinearLayout home1Title;
    @BindView(R.id.material_type)
    TextView materialType;
    @BindView(R.id.material_name)
    TextView materialName;
    @BindView(R.id.material_no)
    TextView materialNo;
    @BindView(R.id.company_address)
    TextView companyAddress;
    @BindView(R.id.one_price_tv)
    TextView price;
    @BindView(R.id.material_price)
    EditText materialPrice;
    @BindView(R.id.send_btn)
    Button sendBtn;
    @BindView(R.id.material_type_rl)
    RelativeLayout materialTypeRl;
    @BindView(R.id.material_name_rl)
    RelativeLayout materialNameRl;
    @BindView(R.id.material_no_rl)
    RelativeLayout materialNoRl;
    @BindView(R.id.company_address_rl)
    RelativeLayout companyAddressRl;
    @BindView(R.id.root_layout)
    LinearLayout root_layout;
    private String address_id;
    private int app_cate_id;
    private OptionsPickerView pvFirstLevel,pvSecondLevel,pvThirdLevel;
    private ArrayList<String> firstLevle,secondLevel,thirdLevel;
    BaseBean<List<LevelThreeClassBean>> oneLevelList;
    List<LevelThreeClassBean.TwoBean> twoLevelList;
    private List<ProvinceBean> options1Items = new ArrayList<>();
    private List<ProvinceBean.TwoRegBean> options2Items = new ArrayList<>();
    private List<ProvinceBean.TwoRegBean.ThreeRegBean> options3Items = new ArrayList<>();
    private String  provinceId = "1";// 省id
    private String cityId = "2";//市 id
    private String distristId = "3";//区id
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private Thread thread;
    private boolean isLoaded = false;
    private String province, city, district;
    List<LevelThreeClassBean.TwoBean.ThreeBean> threeLevelList;
    int threeLevelId,twoLevelId,oneLevelId;
    private int oneLevelType,pvOneType,pvTwoType,twoLevelType;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_send_material_market;
    }

    @Override
    protected void initView() {
        super.initView();
        commonTitle.setText("物资行情发布");
        commonRightImage.setVisibility(View.INVISIBLE);
        commonRightText.setVisibility(View.GONE);
        
        firstLevle = new ArrayList<>();
        secondLevel = new ArrayList<>();
        thirdLevel = new ArrayList<>();
        if(getIntent() != null){
            address_id = getIntent().getStringExtra("address_id");
            app_cate_id = getIntent().getIntExtra("app_cate_id",0);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        Log.d("wuziInfo",address_id+" "+app_cate_id);
        
        initOptions();
        
        getData();
    }

    private void initOptions() {
        pvFirstLevel = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                materialType.setText(firstLevle.get(options1));
                pvOneType = 1;
                oneLevelId = oneLevelList.getData().get(options1).getId();
                secondLevel.clear();
                if(oneLevelList.getData().get(options1).getTwo().size()>= 1){
                    twoLevelList = oneLevelList.getData().get(options1).getTwo();
                    for(int j = 0;j<oneLevelList.getData().get(options1).getTwo().size();j++){
                        secondLevel.add(oneLevelList.getData().get(options1).getTwo().get(j).getName());
                        pvSecondLevel.setPicker(secondLevel);
                    }
                }else{
                    ToastUtils.showT("暂无数据");
                }
                
//                type=options1;
//                tvAllPrice.setText(listType.get(type).getPrice()*mCount+"");
            }
        }).setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.LTGRAY)
                .setCancelColor(Color.GRAY)
                .setSubmitColor(Color.RED)
                .setSubmitText("完成")
                .setTextColorCenter(Color.BLACK)
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();
        
        pvSecondLevel = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                materialName.setText(secondLevel.get(options1));
                twoLevelId = twoLevelList.get(options1).getId();
                pvTwoType = 1;
                if(twoLevelList.get(options1).getThree().size() >= 1){
                    threeLevelList = twoLevelList.get(options1).getThree();
                    for(int a=0;a<twoLevelList.get(options1).getThree().size();a++){
                        thirdLevel.clear();
                        thirdLevel.add(twoLevelList.get(options1).getThree().get(a).getName());
                        pvThirdLevel.setPicker(thirdLevel);
                    }
                }else{
                    ToastUtils.showT("暂无数据");
                }
//                type=options1;
//                tvAllPrice.setText(listType.get(type).getPrice()*mCount+"");
            }
        }).setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.LTGRAY)
                .setCancelColor(Color.GRAY)
                .setSubmitColor(Color.RED)
                .setSubmitText("完成")
                .setTextColorCenter(Color.BLACK)
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();

        pvThirdLevel = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                materialNo.setText(thirdLevel.get(options1));
                threeLevelId = threeLevelList.get(options1).getId();
//                type=options1;
//                tvAllPrice.setText(listType.get(type).getPrice()*mCount+"");
            }
        }).setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.LTGRAY)
                .setCancelColor(Color.GRAY)
                .setSubmitColor(Color.RED)
                .setSubmitText("完成")
                .setTextColorCenter(Color.BLACK)
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();

    }

    //得到物资三级分类
    private void getData() {
        SuperHttp.post("api/myapplication/appMaterialCate")
                .request(new SimpleCallBack<BaseBean<List<LevelThreeClassBean>>>() {
                    @Override
                    public void onSuccess(BaseBean<List<LevelThreeClassBean>> data) {
                        if(data.getCode()==0){
                            //   ToastUtil.showCustomToast("暂无数据");
                            return;
                        }else if(data.getCode()==1){
                            oneLevelList = data;
                            for(int i=0;i<data.getData().size();i++){
                                firstLevle.add(data.getData().get(i).getName());
                                pvFirstLevel.setPicker(firstLevle);
                                
                            }
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        ToastUtils.showT(errMsg);
                    }
                });
    }

    @OnClick({R.id.common_back,R.id.material_type_rl,
            R.id.material_name_rl,R.id.material_no_rl,R.id.company_address_rl,R.id.send_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                finish();
                break;
            case R.id.material_type_rl://物资类型
                oneLevelType = 1;
                if(firstLevle.size()< 1){
                ToastUtils.showT("暂无数据");
                }else{
                    pvFirstLevel.show();
                }
                break;
            case R.id.material_name_rl://物资名称
                if(pvOneType != 1){
                    for(int j = 0;j<oneLevelList.getData().get(0).getTwo().size();j++){
                        secondLevel.add(oneLevelList.getData().get(0).getTwo().get(j).getName());
                        pvSecondLevel.setPicker(secondLevel);
                    }
                }
                if(secondLevel.size() < 1){
                    ToastUtils.showT("暂无数据");
                }else{
                    pvSecondLevel.show();
                }
                
                break;
            case R.id.material_no_rl://物资型号
                if(pvTwoType != 1){
                    for(int j=0;j<oneLevelList.getData().get(0).getTwo().get(0).getThree().size();j++){
                        thirdLevel.add(oneLevelList.getData().get(0).getTwo().get(0).getThree().get(j).getName());
                        pvThirdLevel.setPicker(thirdLevel);
                    }
                }
                if(thirdLevel.size()< 1){
                    ToastUtils.showT("暂无数据");
                }else{
                    pvThirdLevel.show();
                }
                break;
            case R.id.company_address_rl://企业地址
                if (0 != options1Items.size()){
                    if (!FastUtils.isFastDoubleClick()) {
                        //判断软键盘是否打开，为true则关闭，否则不处理
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        boolean isOpen = imm.isActive();
                        if (isOpen) {
                            closrKeyboard();
                        }
                        provinceId = "1";// 省id
                        cityId = "2";//市 id
                        distristId = "3";//区id
                        //城市选择弹出框
                        CityPickerPopWindow2 mPopWindow = new CityPickerPopWindow2(this,options1Items);
                        mPopWindow.showPopupWindow(root_layout);
                        mPopWindow.setCityPickListener(this);
                    }
                }
                break;
            case R.id.send_btn://发布
                releaseGoods();
                break;
        }
    }

    private void releaseGoods() {
        String price = materialPrice.getText().toString();
        Log.d("goodsInfo", Prefer.getInstance().getToken()+" "+oneLevelId+" "+twoLevelId+" "+threeLevelId+" "+provinceId+" "+cityId+" "+distristId);
        SuperHttp.post("api/myapplication/appMaterialAdd")
                .addParam("token",Prefer.getInstance().getToken())
                .addParam("app_cate_id",oneLevelId+"")
                .addParam("app_cate_two",twoLevelId+"")
                .addParam("app_cate_three",threeLevelId+"")
                .addParam("province_id",","+provinceId+",")
                .addParam("city_id",","+cityId+",")
                .addParam("area_id",","+distristId+",")
                .addParam("price",price)
                .addParam("release_days","10")
                .addParam("name",materialNo.getText().toString())
                .request(new SimpleCallBack<BaseBean<GoodsRealseResultBean>>() {
                    @Override
                    public void onSuccess(BaseBean<GoodsRealseResultBean> data) {
                        if(data.getCode() == 1){
                            ToastUtils.showT(data.getMessage());

                            //目前只请求下支付接口，因为发布是要付费的
                            payForPage(data.getData().getOrder());
                        }
                        
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        ToastUtils.showT(errMsg);
                    }
                });
    }

    //发布支付
    private void payForPage(String order){
        Map<String,Object> params = new HashMap<>();
        params.put("token",Prefer.getInstance().getToken());
        params.put("order",order);
        params.put("pay_type","5");//支付类型：1-支付宝;2-微信;3-余额;4-银联支付;5-积分支付
        XUtil.Post(UrlConfig.SUPPLY_FILE_PAY,params,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                finish();
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtils.showT(ex.getMessage());
                super.onError(ex, isOnCallback);
            }
        });
    }

    private void initJsonData(Context context) {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(context, "region.json");//获取assets目录下的json文件数据

        ArrayList<ProvinceBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            List<ProvinceBean.TwoRegBean> CityList = new ArrayList<>();//该省的城市列表（第二级）
            List<ProvinceBean.TwoRegBean.ThreeRegBean> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getTwo_reg().size(); c++) {//遍历该省份的所有城市
                CityList.add(jsonBean.get(i).getTwo_reg().get(c));//添加城市
                List<ProvinceBean.TwoRegBean.ThreeRegBean> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (null == jsonBean.get(i).getTwo_reg().get(c).getThree_reg()
                        || jsonBean.get(i).getTwo_reg().get(c).getThree_reg().size() == 0) {
                    City_AreaList.add(new ProvinceBean.TwoRegBean.ThreeRegBean());
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getTwo_reg().get(c).getThree_reg());
                }
                Province_AreaList.addAll(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.addAll(CityList);

            /**
             * 添加地区数据
             */
            options3Items.addAll( Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData(SendMaterialMarketActivity.this);
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    public ArrayList<ProvinceBean> parseData(String result) {//Gson 解析
        ArrayList<ProvinceBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                ProvinceBean entity = gson.fromJson(data.optJSONObject(i).toString(), ProvinceBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }




    @Override
    public void pickValue(String value) {
        province = value.split("-")[0];
        city = value.split("-")[1];
        if (value.split("-").length >= 3) {
            district = value.split("-")[2];
            companyAddress.setText(province + "-" + city + "-" +district);
        }else {
            district = " ";
            companyAddress.setText(province + "-" + city);
        }

        for (int i = 0; i < options1Items.size(); i++) {
            if (province.equals(options1Items.get(i).getName())) {
                provinceId = options1Items.get(i).getId() + "";
            }
        }

        for (int i = 0; i < options2Items.size(); i++) {
            if ((options2Items.get(i).getName().contains(city))){
                cityId = options2Items.get(i).getId() + "";
            }
        }

        if (null != options3Items && 0 != options3Items.size()) {
            for (int i = 0; i < options3Items.size(); i++) {

                if (!TextUtils.isEmpty(district) && options3Items.get(i).getName().contains(district)) {
                    distristId = options3Items.get(i).getId() + "";
                }
            }
        }else {
            distristId = " ";
        }

        Log.e("TAGPROVINCE_ID", provinceId + ":" + cityId + ":" + distristId);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

}
